package util

import (
	"gin-demo/pkg/setting"
	"github.com/dgrijalva/jwt-go"
	"time"
)

// jwt 秘钥
var jwtSecret = []byte(setting.JwtSecret)

type JwtAuth struct {
	ID int `json:"id"`
	jwt.StandardClaims
}

// GenerateToken 生成token
func GenerateToken(id int) (string, error) {
	nowTime := time.Now()
	expireTime := nowTime.Add(30 * 24 * 7 * time.Hour)

	jwtAuth := JwtAuth{
		id,
		jwt.StandardClaims{
			ExpiresAt: expireTime.Unix(),
			Issuer:    "gin-blog",
		},
	}

	tokenClaims := jwt.NewWithClaims(jwt.SigningMethodHS256, jwtAuth)
	token, err := tokenClaims.SignedString(jwtSecret)

	return token, err
}

// ParseToken 解析token
func ParseToken(token string) (*JwtAuth, error) {
	tokenClaims, err := jwt.ParseWithClaims(token, &JwtAuth{}, func(token *jwt.Token) (interface{}, error) {
		return jwtSecret, nil
	})

	if tokenClaims != nil {
		if claims, ok := tokenClaims.Claims.(*JwtAuth); ok && tokenClaims.Valid {
			return claims, nil
		}
	}

	return nil, err
}
